home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: Paul Roub <proub@shadow.net>
- Newsgroups: comp.lang.c,comp.lang.c.moderated
- Subject: Re: Leading and Trailing Blanks
- Date: 5 Jan 1996 09:53:15 -0600
- Organization: Crash Basket
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4cjhhb$f8s@solutions.solon.com>
- References: <4chh1b$685@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
- X-Mailer: Mozilla 2.0b4 (Win95; I)
-
-
- Casey Claiborne wrote:
- >
- > Hello -
- > I am wondering if anyone out there has a program (or knows of one)
- > that allows one to strip leading and trailing blanks from a string.
- > ex:
- >
-
- Here's the way I do it. This is a bit verbose, but I was going for
- clarity, not conciseness. Use it along the lines of:
-
- char test[ 10 ];
-
- strcpy( test, " test " );
- lrtrim( test );
-
- [Replaced //foo\n with /*foo */\n in entire document, for C content. -mod]
-
- /* test now contains "test" */
-
- /* Function: void lrtrim() */
- /* */
- /* Description: remove leading and trailing blanks from a */
- /* string, in place all leading and trailing */
- /* whitespace is removed */
- /* */
- /* Parameters: char *st - string to trim */
- /* */
- void lrtrim( char *st )
- {
- {
- /* pointer to last non-space char seen */
- /* */
- char *lastNonBlank = st - 1;
-
-
- /* pointer to left-trimmed string */
- /* */
- char *newString;
-
- /* pointer to original string */
- /* */
- char *oldString;
-
- /* initially, assume we're starting at the beginning */
- /* */
- newString = oldString = st;
-
- /* skip leading blanks to find the new starting char */
- /* */
- while (isspace( *oldString ))
- ++oldString;
-
- /* now copy all characters, starting from the first non-blank, */
- /* to the beginning of the string. e.g., if the string was " */
- /* test", then newString would be pointing at the first 't', */
- /* while oldString would be pointing at the first space */
- /* */
- /* additionally, always keep track of the location (in the new */
- /* string) of the last non-space character seen. initially, */
- /* this is set to one char before the beginning of the string, */
- /* since we haven't seen any yet */
- /* */
- while (*oldString != '\0')
- {
- if (! isspace( *oldString )) /* non-space? */
- lastNonBlank = newString; /* note it */
-
- *newString++ = *oldString++; /* move the char */
- }
-
- /* the last non-blank should be our last character. put a 0 */
- /* terminator *after* it. if we never saw a non-blank, this */
- /* puts the term at the first position of the string -- just */
- /* what we want */
- /* */
- lastNonBlank[ 1 ] = '\0';
-
- return;
- }
- }
-
-
-
- -paul
-